package com.tanhua.app.service;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.MovementsApi;
import com.tanhua.api.mongo.RecommendUserApi;
import com.tanhua.db.User;
import com.tanhua.db.UserInfo;
import com.tanhua.mongo.Visitors;
import com.tanhua.vo.UserHolder;
import com.tanhua.vo.VisitorsVo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MovementsService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Reference
    private MovementsApi movementsApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private RecommendUserApi recommendUserApi;

    public ResponseEntity findVisitors() {

        String time = stringRedisTemplate.opsForValue().get("visitors_user_" + UserHolder.getUser().getId());
        List<VisitorsVo> visitorsVoList = new ArrayList<>();
        if (time != null) {
            List<Visitors> visitorsList = movementsApi.visitors(UserHolder.getUser().getId(), Long.valueOf(time));
            if (CollectionUtil.isNotEmpty(visitorsList)) {

                for (Visitors visitors : visitorsList) {
                    UserInfo userInfo = userInfoApi.findByUserId(visitors.getVisitorUserId());
                    VisitorsVo visitorsVo = new VisitorsVo();
                    //封装访客信息
                    visitorsVo.setUserInfo(userInfo);
                    //取缘分值
                    Long score = recommendUserApi.findScore(visitors.getVisitorUserId(), UserHolder.getUser().getId());
                    visitorsVo.setFateValue(score);
                    visitorsVoList.add(visitorsVo);
                }
            }
        }
        // 3 没有：将当前时间作为当前用户的最后一次登录时间
        stringRedisTemplate.opsForValue().set("visitors_user_" + UserHolder.getUser().getId(), System.currentTimeMillis() + "");

        return ResponseEntity.ok(visitorsVoList);
    }
}
